#include <crypt.h>
#include <pwd.h>
#include <shadow.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>

#include "password.h"

int get_encrypted_password(const char *username, char *encrypted_password) {
  struct spwd *code_staus;
  code_staus = getspnam(username);
  if (!code_staus) {
    perror("getspnam");
    return -1;
  }
  strcpy(encrypted_password, code_staus->sp_pwdp);
  return 0;
}

int password_encrypt(const char *username, const char *cleartext_password,
                     char *encrypted_password) {
  char passwd[128];
  get_encrypted_password(username, passwd);

  /* printf("inpass = %s\n", passwd); */

  int idx = strlen(passwd) - 1;
  while (passwd[idx] != '$') {
    --idx;
  }

  char salt[128] = {0};

  memcpy(salt, passwd, idx + 1);
  /* printf("salt = %s\n", salt); */
  strcpy(encrypted_password, crypt(cleartext_password, salt));
  /* printf("enpass = %s\n", encrypted_password); */

  return 0;
}
